package com.stbu.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.*;

@Controller
public class FileController {

    @RequestMapping("/toUpload")
    public String toUploadJsp() {
        return "upload";
    }

    @RequestMapping("/upload")
    public ModelAndView upload(@RequestPart("myfile") MultipartFile file) {
        ModelAndView view =new ModelAndView();
        String destFileStr = "D:" + File.separator+ "FileIo" + File.separator;
        File destFile = new File(destFileStr);
        if (!destFile.exists()){
            destFile.mkdir();
        }
        System.out.println("目标地址：" + destFile.getAbsolutePath());

        File destFinalFile = new File(destFile,file.getOriginalFilename());
        System.out.println("文件的全路径：" + destFinalFile.getAbsolutePath());
        String msg = "";
        try {
            file.transferTo(destFinalFile);
            msg = "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            msg = "上传失败";
        }
        view.addObject("msg",msg);
        view.setViewName("info");
        return view;
    }

    @RequestMapping("/toDownload")
    public String toDownload() {
        return "download";
    }

    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(@RequestParam("filename") String filename) throws Exception {
        String destFileStr = "D:" + File.separator+ "FileIo" + File.separator + filename;
        File destFile = new File(destFileStr);
        InputStream in = new FileInputStream(destFile);
        byte[] body = new byte[in.available()];
        in.read(body);
        MultiValueMap<String,String> head = new LinkedMultiValueMap<>();
        head.add("Content-Dispositon","attchement;filename='" + destFile.getName()+"'");
        HttpStatus status = HttpStatus.OK;
        in.close();
        ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body,head,status);
        return entity;
    }
}
